//Copyright (c) 2007 Andrew Badera andrew@badera.us
//SVN repository at http://powncenet.googlecode.com/svn/

//Permission is hereby granted, free of charge, to any person
//obtaining a copy of this software and associated documentation
//files (the "Software"), to deal in the Software without
//restriction, including without limitation the rights to use,
//copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the
//Software is furnished to do so, subject to the following
//conditions:

//The above copyright notice and this permission notice shall be
//included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

using BadException;

namespace BadWeb
{
    public class Get
    {
        public static string USER_AGENT = "PownceNET/0.1 +http://code.google.com/p/powncenet/";

        public static string DoGet(string url, string contentType)
        {
            return DoGet(url, contentType, string.Empty, string.Empty);
        }

        public static string DoGet(string url, string contentType, string username, string password)
        {
            string bunk = string.Empty;

            return DoGet(url, contentType, username, password, ref bunk);
        }

        public static string DoGet(string url, string contentType, string username, string password, ref string sessionID)
        {
            return DoGet(url, null, null, contentType, username, password, "Basic", ref sessionID);
        }

        public static string DoGet(string url, List<HttpVar> vars, List<HttpHeader> headers, string contentType, string username, string password, string authType, ref string sessionID)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentException("Must provide url.");
            }

            string qs = string.Empty;

            if (null!=vars && vars.Count > 0)
            {
                qs = HttpVar.GetVars(vars);
            }

            StringBuilder urlBuilder = new StringBuilder();

            urlBuilder.Append(url);

            if (qs.Length > 0)
            {
                if (url.Contains("?"))
                {
                    urlBuilder.Append(string.Concat(new object[] { "&", qs }));
                }
                else
                {
                    urlBuilder.Append(string.Concat(new object[] { "?", qs }));
                }
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());

            if (!string.IsNullOrEmpty(username))
            {
                CredentialCache credCache = new CredentialCache();
                credCache.Add(new Uri(urlBuilder.ToString()), authType,
                          new NetworkCredential(username, password));

                request.Credentials = credCache;
            }

            request.Method = "GET";
            request.UserAgent = USER_AGENT;
            if (contentType.Trim().Length > 0)
            {
                request.ContentType = contentType;
            }

            request.ProtocolVersion = new System.Version("1.1");

            StringBuilder sb = new StringBuilder();

            byte[] buf = new byte[8192];

            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                BadLogger.WriteToLog("Get.DoGet", ex, ExceptionEnums.LogEntryType.Error);
                throw ex;
            }

            try
            {
                string sessIDHeader = response.Headers["Set-Cookie"];
                string[] sessIDVals = sessIDHeader.Split(new char[] { ';' });
                string sessKeyPair = sessIDVals[0];
                sessionID = (sessKeyPair.Split(new char[] { '=' }))[1];
            }
            catch { }

            Stream resStream = response.GetResponseStream();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                string message = string.Format("Could not GetResponseStream(); code: {0}.", response.StatusCode.ToString());

                BadLogger.WriteToLog("Get.DoGet", message, ExceptionEnums.LogEntryType.Error);
                
                throw new HttpException(message);
            }
            
            string tempString = null;
            int count = 0;

            do
            {
                count = resStream.Read(buf, 0, buf.Length);

                if (count != 0)
                {
                    tempString = Encoding.ASCII.GetString(buf, 0, count);

                    sb.Append(tempString);
                }
            }
            while (count > 0);

            string responseContent = sb.ToString();


            return responseContent;
        }

    }
}

